#coding:utf-8
from lxml import etree
import time,requests
from selenium import webdriver

def get_cookies():
    print('启动浏览器')
    try:
        with open('C:/zhihucookie.txt', 'r+') as cookie_txt:
            return str(cookie_txt.readlines())
    except  Exception :
        print('本地没有cookie文件，需要重新登录')
        driver = webdriver.Chrome()
        driver.get('https://www.zhihu.com/#signin')
        print(driver.title)
        while '首页' not in driver.title:
            print('请尽快登录')
            time.sleep(3)
        print(driver.title,driver.get_cookies(),driver.current_url)
        cookie = [item["name"] + "=" + item["value"] for item in driver.get_cookies()]
        cookiestr = ';'.join(item for item in cookie)
        with open('C:/zhihucookie.txt', 'w') as cookie_txt:
            cookie_txt.write(cookiestr)
        return cookiestr
def get_zhihu():
    Cookie=get_cookies()
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36',
    'Host':'www.zhihu.com','cookie':Cookie}
    print(headers)

    session = requests.Session()
    response=session.get('https://www.zhihu.com/',headers=headers)
    response = session.get('https://www.zhihu.com/', headers=headers)
    with open('C:/zhihu.html', 'w',encoding='utf-8') as cookie_txt:
        cookie_txt.write(response.text)
    if '首页 - 知乎' in etree.HTML(response.text).xpath('/html/head/title/text()'):
        print('登录成功','响应码', response.status_code, '首页内容：', response.text)

if __name__ == '__main__':
    get_zhihu()